<?php

use Symfony\Component\Filesystem\Filesystem;

 class EduSohoUpgrade extends AbstractUpdater
 {
     public function update()
     {
        $this->getConnection()->beginTransaction();
        try{
            $this->installRouting();
            $this->installAssets();

            $this->createService('System.SettingService')->set('question_plus', array(
              'enabled'=> 1,
            ));


            $this->getConnection()->commit();
        } catch(\Exception $e) {
            $this->getConnection()->rollback();
            throw $e;
        }
     }

    public function installRouting()
    {
        $config = <<<EOT


_plugin_questionplus_web:
    resource: "@QuestionPlusBundle/Resources/config/routing.yml"
    prefix:   /

_plugin_questionplus_admin:
    resource: "@QuestionPlusBundle/Resources/config/routing_admin.yml"
    prefix:   /admin
EOT;
        $filepath = $this->kernel->getParameter('kernel.root_dir') . '/config/routing_plugins.yml';
        file_put_contents($filepath, $config, FILE_APPEND);
    }

    private function installAssets()
    {
        $rootDir = realpath($this->kernel->getParameter('kernel.root_dir') . '/../');

        $originDir = "{$rootDir}/plugins/QuestionPlus/QuestionPlusBundle/Resources/public";
        $targetDir = "{$rootDir}/web/bundles/questionplus";

        $filesystem = new Filesystem();

        if ($filesystem->exists($targetDir)) {
            $filesystem->remove($targetDir);
        }

        $filesystem->mirror($originDir, $targetDir, null, array('override' => true, 'delete' => true));
    }

 }


 abstract class AbstractUpdater
 {
    protected $kernel;
    public function __construct ($kernel)
    {
        $this->kernel = $kernel;
    }

    public function getConnection()
    {
        return $this->kernel->getConnection();
    }

    protected function createService($name)
    {
        return $this->kernel->createService($name);
    }

    protected function createDao($name)
    {
        return $this->kernel->createDao($name);
    }

    abstract public function update();
   
 }